package com.yan.crowd.controller;

import com.yan.crowd.util.ResultEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
public class RedisProviderController {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @RequestMapping("/set/redis/key/value/remote")
    public ResultEntity<String> setRedisKeyValueRemote(@RequestParam("key") String key, @RequestParam("value") String value) {
        try {
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            operations.set(key, value);
            return ResultEntity.successWithoutData();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.failed(e.getMessage());
        }
    }

    @RequestMapping("/set/redis/key/value/with/timeout/remote")
    public ResultEntity<String> setRedisKeyValueWithTimeoutRemote(@RequestParam("key") String key,
                                                                  @RequestParam("value") String value,
                                                                  @RequestParam("time") long time,
                                                                  @RequestParam("timeunit") TimeUnit timeUnit) {
        try {
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            operations.set(key, value, time, timeUnit);
            return ResultEntity.successWithoutData();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.failed(e.getMessage());
        }
    }

    @RequestMapping("/get/redis/key")
    public ResultEntity<String> getRedisKey(@RequestParam("key") String key) {

        try {
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            String s = operations.get(key);
            return ResultEntity.successWithData(s);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.failed(e.getMessage());
        }

    }

    @RequestMapping("/delete/redis/key")
    public ResultEntity<String> deleteRedisKey(@RequestParam("key") String key) {
        try {
            stringRedisTemplate.delete(key);
            return ResultEntity.successWithoutData();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.failed(e.getMessage());
        }
    }

}
